package com.qdxwx.common.utils;


import com.aliyun.vod.upload.impl.UploadVideoImpl;
import com.aliyun.vod.upload.req.UploadStreamRequest;
import com.aliyun.vod.upload.req.UploadVideoRequest;
import com.aliyun.vod.upload.resp.UploadStreamResponse;
import com.aliyun.vod.upload.resp.UploadVideoResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.vod.model.v20170321.*;
import com.qdxwx.common.json.AjaxResult;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Qdx NetSchool Platform
 * @author qdxwx
 * @updateTime 2022/5/25
 * @description
 */
public class AliyunUtils {

    public static void main(String[] args) {
        String fileUrl = "http://vod.example.com/video/standard/test.mp4";
        //Url鉴权密钥
        Map<String, Object> config = new HashMap<>();
        config.put("privateKey", "kjsdfoi398sdfekjnsdf012");
        System.out.println(getAuthURL(fileUrl, config));
    }

    //将Url转换为鉴权Url
    public static String getAuthURL(String fileUrl, Map<String, Object> config) {
        if (TKString.isEmpty(config.get("privateKey"))) {
            return fileUrl;
        }
        String fileName;
        if (fileUrl.contains(".com/")) {
            fileName = fileUrl.substring(fileUrl.indexOf(".com/") + 4);
        } else if (fileUrl.contains(".cn/")) {
            fileName = fileUrl.substring(fileUrl.indexOf(".cn/") + 3);
        } else if (fileUrl.contains(".net/")) {
            fileName = fileUrl.substring(fileUrl.indexOf(".net/") + 4);
        } else if (fileUrl.contains("://")) {
            fileName = fileUrl.substring(fileUrl.indexOf("://") + 3);
            fileName = fileName.substring(fileName.indexOf("/"));
        } else {
            fileName = fileUrl;
        }
        //3600s 过期时间1小时
        long timeStamp = System.currentTimeMillis() / 1000 + 3600;
        String md5Value = TKConvert.toMD5(String.format("%s-%s-%s-%s-%s", fileName, timeStamp, 0, 0, config.get("privateKey")));
        if (fileUrl.contains("?")) {
            return String.format("%s&auth_key=%s-%s-%s-%s", fileUrl, timeStamp, 0, 0, md5Value);
        } else {
            return String.format("%s?auth_key=%s-%s-%s-%s", fileUrl, timeStamp, 0, 0, md5Value);
        }
    }

    /**
     * 获取阿里云地址（带鉴权）
     * @param config
     * @param videoId
     * @return
     */
    public static String getPlayURL(Map<String, Object> config, String videoId) {
        String fileUrl = getPlayURL((String) config.get("accessKeyId"),(String) config.get("accessKeySecret"), videoId);
        if (TKString.isEmpty(fileUrl)) return null;
        return getAuthURL(fileUrl, config);
    }

    /**
     * 获取阿里云地址（不带鉴权）
     * @param accessKeyId
     * @param accessKeySecret
     * @param videoId
     * @return
     */
    public static String getPlayURL(String accessKeyId, String accessKeySecret, String videoId) {
        String url = null;
        if (TKString.isEmpty(videoId)) return url;
        DefaultProfile profile = DefaultProfile.getProfile("cn-Shanghai", accessKeyId, accessKeySecret);
        IAcsClient client = new DefaultAcsClient(profile);
        GetPlayInfoRequest request = new GetPlayInfoRequest();
        // 视频ID。
        request.setVideoId(videoId);
        try {
            GetPlayInfoResponse response = client.getAcsResponse(request);
            List<GetPlayInfoResponse.PlayInfo> playInfo = response.getPlayInfoList();
            if (playInfo.size() > 1) {
                //m3u8格式
                url = playInfo.get(1).getPlayURL();
            } else {
                //mp4格式
                url = playInfo.get(0).getPlayURL();
            }
        } catch (ClientException e) {
            System.out.println("ErrCode:" + e.getErrCode());
            System.out.println("ErrMsg:" + e.getErrMsg());
            return null;
        }
        return url;
    }

    public static String uploadLocal(Map<String, String> config, String titleName, String fileName) {
        String accessKeyId = config.get("accessKeyId");
        String accessKeySecret = config.get("accessKeySecret");
        return uploadLocal(accessKeyId, accessKeySecret, titleName, fileName);
    }

    /**
     * 本地文件上传接口
     *
     * @param accessKeyId
     * @param accessKeySecret
     * @param title
     * @param fileName
     */
    public static String uploadLocal(String accessKeyId, String accessKeySecret, String title, String fileName) {
        UploadVideoRequest request = new UploadVideoRequest(accessKeyId, accessKeySecret, title, fileName);
        /* 可指定分片上传时每个分片的大小，默认为2M字节 */
        request.setPartSize(2 * 1024 * 1024L);
        /* 可指定分片上传时的并发线程数，默认为1，(注：该配置会占用服务器CPU资源，需根据服务器情况指定）*/
        request.setTaskNum(1);
        UploadVideoImpl uploader = new UploadVideoImpl();
        UploadVideoResponse response = uploader.uploadVideo(request);
        System.out.print("RequestId=" + response.getRequestId() + "\n");  //请求视频点播服务的请求ID
        System.out.print("VideoId=" + response.getVideoId() + "\n");
        if (response.isSuccess()) {
            return response.getVideoId();
        } else {
            System.out.print("ErrorCode=" + response.getCode() + "\n");
            System.out.print("ErrorMessage=" + response.getMessage() + "\n");
        }
        return "";
    }


    /**
     * 提交智能审核作业
     */
    public static SubmitAIMediaAuditJobResponse submitAIMediaAuditJob(DefaultAcsClient client, String videoId) throws Exception {
        SubmitAIMediaAuditJobRequest request = new SubmitAIMediaAuditJobRequest();
        // 设置视频ID
        request.setMediaId(videoId);
        // 返回结果
        return client.getAcsResponse(request);
    }

    // 初始化客户端
    public static DefaultAcsClient initVodClient(String accessKeyId, String accessKeySecret) throws ClientException {
        // 点播服务接入区域,此处要根据阿里云配置填写，对不上部分功能会用不了
        String regionId = "cn-shanghai";
        DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret);
        return new DefaultAcsClient(profile);
    }

    // 删除点播视频
    public static AjaxResult deleteVideo(String videoId, Map<String, Object> aliMap) {
        try {
            DefaultAcsClient client = initVodClient(aliMap.get("accessKeyId").toString(), aliMap.get("accessKeySecret").toString());
            DeleteVideoRequest request = new DeleteVideoRequest();
            request.setVideoIds(videoId);
            client.getAcsResponse(request);
            return AjaxResult.success();
        } catch (Exception e) {
            return AjaxResult.error();
        }
    }


    /**
     * 流式上传接口
     *
     * @param accessKeyId
     * @param accessKeySecret
     * @param title
     * @param fileName
     * @param inputStream
     */
    public static String uploadStream(String accessKeyId, String accessKeySecret, String title, String fileName, InputStream inputStream) {
        UploadStreamRequest request = new UploadStreamRequest(accessKeyId, accessKeySecret, title, fileName, inputStream);
        UploadVideoImpl uploader = new UploadVideoImpl();
        UploadStreamResponse response = uploader.uploadStream(request);
        if (response.isSuccess()) {
            return response.getVideoId();
        } else {
            System.out.print("ErrorCode=" + response.getCode() + "\n");
            System.out.print("ErrorMessage=" + response.getMessage() + "\n");
        }
        return "";
    }
}




